<template>
  <div>
    PromiseTest
  </div>
</template>

<script>
export default {
  name: 'PromiseTest',
  props: {

  },
  data() {
    return {

    };
  },
  computed: {

  },
  created() {
    // this.test()
    this.principle()
  },
  methods: {
    handleCheckAllChange(value, item) {
      let labels = []
      item.imgList.map(x => {
        labels.push(x.sortKey)
      })
      this.checkedimgs = value ? labels : [];
      item.isIndeterminate = false;
    },
    handlecheckedimgsChange(value, item) {
      let checkedCount = value.length;
      item.checkAll = checkedCount === item.imgList.length;
      item.isIndeterminate = checkedCount > 0 && checkedCount < item.imgList.length;
    },
    test() {
      let boilwater = function () {
        return new Promise(function (resolve, reject) {
          setTimeout(() => {
            console.log(new Date())
            resolve('boilwater')
          }, 2000);
        })
      }
      let washGlass = function () {
        return new Promise(function (resolve, reject) {
          setTimeout(() => {
            console.log(new Date())
            resolve('washGlass')
          }, 3000)
        })
      }
      let tea = function () {
        return new Promise(function (resolve, reject) {
          setTimeout(() => {
            console.log(new Date())
            resolve('泡茶')
          }, 5000)
        })
      }
      /** 
      实现同步调用
      */
      // boilwater().then(function(a){
      //   console.log(a)
      //   return washGlass(a)
      // }).then(function(a){
      //   console.log(a)
      //   return tea(a)
      // }).then(function(a){
      //   console.log(a)
      // })
      /**
      异步调用
       */
      Promise.all([boilwater(), washGlass(), tea()]).then(function () {
        console.log('完成')
      })
    },
    principle() {
      // promise实现流程,异步调用
      let MyPromise = function (fn) {
        let callBack = null
        this.then = function (cb) {
          // 异步关键之处----赋值callback
          callBack = cb
        }
        function resolve(data) {
          // then的调用要在后面执行，将低优先级*****
          setTimeout(function () {
            callBack(data)
          }, 0)
        }
        fn(resolve)
      }
      let eating = function () {
        return new MyPromise(function (resolve, reject) {
          // resolve('吃饭中')
          // 异步关键之处----隔几秒调用
          // setTimeout(() => {
          //   resolve('吃饭中')
          // }, 2000)
          resolve('吃饭中')
        });
      }
      eating().then(function (data) {
        console.log(data)
      })
    },
    chain() {
      /**
      链式调用原理（支持多个then回调）队列
       */

    }
  },
  watch: {

  },
  components: {

  }
};
</script>
<style lang="less">

</style>
